package com.example.fengyungo_user.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItemV2;
import com.amap.api.services.poisearch.PoiResultV2;
import com.amap.api.services.poisearch.PoiSearchV2;
import com.amap.api.services.route.DistanceItem;
import com.amap.api.services.route.DistanceResult;
import com.amap.api.services.route.DistanceSearch;
import com.example.fengyungo_user.R;
import com.example.fengyungo_user.activity.BaseActivity;
import com.example.fengyungo_user.adapter.LocationAdapter;
import com.example.fengyungo_user.constant.MapConstant;
import com.example.fengyungo_user.domain.Location;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 徐
 */
public class EndActivity extends BaseActivity implements PoiSearchV2.OnPoiSearchListener, DistanceSearch.OnDistanceSearchListener {

    private static final String TAG = "EndActivity";

    /**
     * 输入终点
     */
    private EditText endEt;
    /**
     * 搜索按钮
     */
    private LinearLayout mapLinearLayout;
    /**
     * 搜索结果的经纬度
     */
    private List<LatLonPoint> latLonPoints;
    /**
     * PoiItemV2-ArrayList
     */
    private ArrayList<PoiItemV2> pois;
    /**
     * PoiSearchV2.Query
     */
    private PoiSearchV2.Query query;
    /**
     * PoiSearch 对象
     */
    private PoiSearchV2 poiSearch;
    /**
     * 起点坐标
     */
    private LatLonPoint beginLatLonPoint;
    /**
     * DistanceSearch
     */
    private DistanceSearch distanceSearch;
    /**
     * 起点与所有结果的距离，Integer-起点序号，Float-距离
     */
    private Map<Integer, Float> resultDistances;
    /**
     * 显示结果的适配器
     */
    private LocationAdapter adapter;
    /**
     * RecyclerView
     */
    private RecyclerView recyclerView;
    /**
     * 显示的地点与距离
     */
    private List<Location> locations;
    /**
     * LinearLayoutManager
     */
    private LinearLayoutManager layoutManager;
    /**
     * ProgressBar
     */
    private ProgressBar progressBar;
    /**
     * 起点位置String
     */
    private String beginPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_end);

        resultDistances = new HashMap<>();

        // 获取来自MainFragment的intent的数据
        getIntentDataFromMainFragment();

        endEt = findViewById(R.id.et_end);
        mapLinearLayout = findViewById(R.id.linearlayout_map);
        progressBar = findViewById(R.id.progress_bar);

        recyclerView = findViewById(R.id.recyclerview_end);
        layoutManager = new LinearLayoutManager(this);

        // 返回
        ImageButton back = findViewById(R.id.back);
        back.setOnClickListener((view -> {
            finish();
        }));

        // 初始化测距
        initCalculateRoute();

        // 在输入的过程中搜索地点
        endEt.addTextChangedListener(setTextWatcher());

        mapLinearLayout.setOnClickListener((v) -> {
            // 地图选点
            Intent intent = new Intent(this,PositionSelectActivity.class);
            intent.putExtra(MapConstant.BEGIN_LAT, beginLatLonPoint.getLatitude());
            intent.putExtra(MapConstant.BEGIN_LON, beginLatLonPoint.getLongitude());
            intent.putExtra(MapConstant.BEGIN_ADDRESS, beginPosition);
            startActivity(intent);
        });
    }

    /**
     * 获取来自MainFragment的intent携带的数据
     */
    private void getIntentDataFromMainFragment() {
        Intent intent = getIntent();
        double beginLat = intent.getDoubleExtra(MapConstant.BEGIN_LAT, 0);
        double beginLon = intent.getDoubleExtra(MapConstant.BEGIN_LON, 0);
        beginLatLonPoint = new LatLonPoint(beginLat, beginLon);
        beginPosition = intent.getStringExtra(MapConstant.BEGIN_ADDRESS);
        Log.d(TAG, "getIntentDataFromMainFragment: beginLatLonPoint=" + beginLatLonPoint);
    }

    /**
     * 设置textWatch以在EditText输入的时候执行搜索
     */
    private TextWatcher setTextWatcher() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String keyWord = endEt.getText().toString();
                // 为空则不进行查询
                if ("".equals(keyWord)) {
                    return;
                }
                int currentPage = 0;
                // 显示加载中
                progressBar.setVisibility(View.VISIBLE);
                Log.d(TAG, "onCreate: progress=" + progressBar.getVisibility());
                // 搜索地点
                searchPosition(keyWord, currentPage);
            }
        };
    }

    /**
     * 根据关键词查询，发送请求
     *
     * @param keyWord     地名关键字
     * @param currentPage 查询页码
     */
    private void searchPosition(String keyWord, int currentPage) {

        query = new PoiSearchV2.Query(keyWord, "", "");
        //keyWord表示搜索字符串，
        //第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
        //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索

        //设置查询页码
        query.setPageNum(currentPage);
        // 设置查询每页的结果数目
        query.setPageSize(100);

        try {
            poiSearch = new PoiSearchV2(this, query);
            poiSearch.setOnPoiSearchListener(this);
        } catch (AMapException e) {
            e.printStackTrace();
            // 失败
            Toast.makeText(this, e.getErrorMessage(), Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
        poiSearch.searchPOIAsyn();
    }

    /**
     * 初始化测距
     */
    private void initCalculateRoute() {
        // 初始化 DistanceSearch 对象
        try {
            distanceSearch = new DistanceSearch(this);
        } catch (AMapException e) {
            e.printStackTrace();
            // 失败
            Toast.makeText(this, e.getErrorMessage(), Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
        // 设置数据回调监听器
        distanceSearch.setDistanceSearchListener(this);
    }

    /**
     * 发送请求进行测距
     *
     * @param origins 起点
     */
    private void calculateRouteDistance(List<LatLonPoint> origins) {
        DistanceSearch.DistanceQuery distanceQuery = new DistanceSearch.DistanceQuery();
        // 设置搜索参数
        distanceQuery.setOrigins(origins);
        distanceQuery.setDestination(beginLatLonPoint);
        //设置测量方式，支持直线和驾车
        distanceQuery.setType(DistanceSearch.TYPE_DRIVING_DISTANCE);
        // 发送请求，进行距离测量计算
        distanceSearch.calculateRouteDistanceAsyn(distanceQuery);
    }

    /**
     * 通过回调接口 onPoiSearched 解析searchPOIAsyn返回的结果
     *
     * @param poiResultV2 PoiResultV2
     * @param i           int
     */
    @Override
    public void onPoiSearched(PoiResultV2 poiResultV2, int i) {
        // 返回结果成功或者失败的响应码。1000为成功，其他为失败
        Log.d(TAG, "onPoiSearched: i=" + i);
        if (i == MapConstant.RESULT_SUCCESS) {

            // 获取到PoiItem列表
            pois = poiResultV2.getPois();
            Log.d(TAG, "onPoiSearched: pois=" + pois);

            latLonPoints = new ArrayList<>();
            for (PoiItemV2 poiItemV2 : pois) {
                latLonPoints.add(poiItemV2.getLatLonPoint());
            }
            // 测距
            calculateRouteDistance(latLonPoints);
            Log.d(TAG, "onPoiSearched: latLonPoints=" + latLonPoints);
        } else {
            Log.d(TAG, "onPoiSearched: failed");
            // 失败
            Toast.makeText(this, MapConstant.GET_POSITION_FAILED, Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItemV2 poiItemV2, int i) {
        Log.d(TAG, "onPoiItemSearched: i=" + i);
        Log.d(TAG, "onPoiItemSearched: poiItemV2=" + poiItemV2);
    }

    /**
     * 在 DistanceSearch.OnDistanceSearchListener 接口回调方法
     * onDistanceSearched(DistanceResult distanceResult, int errorCode) 处理距离测量结果。
     * 返回的信息中您可以获得预估的直线或驾车路线距离。
     *
     * @param distanceResult DistanceResult
     * @param i              code
     */
    @Override
    public void onDistanceSearched(DistanceResult distanceResult, int i) {
        Log.d(TAG, "onDistanceSearched: i=" + i);
        if (i == MapConstant.RESULT_SUCCESS) {
            // result.getDistanceResults()可以获取到 DistanceItem 列表
            List<DistanceItem> distanceResults = distanceResult.getDistanceResults();

            // 多起点，一终点
            for (DistanceItem result : distanceResults) {
                // 起点坐标，起点坐标序列号（从１开始）
                resultDistances.put(result.getOriginId(), result.getDistance());
                Log.d(TAG, "onDistanceSearched: originId=" + result.getOriginId());
            }
            Log.d(TAG, "onDistanceSearched: resultDistances=" + resultDistances);

            // 通过recyclerView展示终点与距离
            locations = new ArrayList<>();
            for (Map.Entry<Integer, Float> entry : resultDistances.entrySet()) {
                Location location = new Location();
                int key = entry.getKey();
                location.setEndPosition(pois.get(key-1).toString());
                location.setDistance(resultDistances.get(key) + MapConstant.DISTANCE_M);
                location.setEndLatLonPoint(pois.get(key-1).getLatLonPoint());
                location.setBeginLatLonPoint(beginLatLonPoint);
                location.setBeginPosition(beginPosition);
                locations.add(location);
            }
            Log.d(TAG, "onDistanceSearched: locations=" + locations);
            recyclerView.setLayoutManager(layoutManager);
            adapter = new LocationAdapter(locations);
            recyclerView.setAdapter(adapter);
            // 加载完成
            progressBar.setVisibility(View.GONE);
            resultDistances.clear();
        } else {
            // 失败
            Toast.makeText(this, MapConstant.GET_POSITION_FAILED, Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
    }
}